package com.css.dzj.dzjap.modules.record.community.service.impl;

import com.css.dzj.dzjap.common.util.Constant;

import com.css.dzj.dzjap.common.util.ServiceUtil;
import com.css.dzj.dzjap.modules.info.service.ConstrService;
import com.css.dzj.dzjap.modules.publick.dao.PublicDao;
import com.css.dzj.dzjap.modules.publick.entity.ApPublicEntity;
import com.css.dzj.dzjap.modules.record.approject.entity.ApRecordEntity;
import com.css.dzj.dzjap.modules.record.approject.entity.QApRecordEntity;
import com.css.dzj.dzjap.modules.record.community.entity.ApRecordGainEntity;
import com.css.dzj.dzjap.modules.record.community.entity.QApRecordGainEntity;
import com.css.dzj.dzjap.modules.record.community.mapper.CommunityMapper;
import com.css.dzj.dzjap.modules.record.community.service.CommunityRecordService;
import com.css.dzj.dzjap.modules.todolist.entity.ApTodoEntity;
import com.css.dzj.dzjap.modules.todolist.mapper.ApTodoMapper;
import com.css.dzj.dzjap.modules.todolist.service.ApTodoService;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommunityRecordServiceImpl implements CommunityRecordService {
    @Autowired
    private CommunityMapper communityMapper;
    @Autowired
    private ApTodoService apTodoService;

    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private PublicDao publicDao;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ApTodoMapper apTodoMapper;
    @Autowired
    private ConstrService constrService;

    @Override
    public Page<ApRecordGainEntity> getAllPage(Pageable pageable) {
        Page<ApRecordGainEntity> all = communityMapper.findAll(pageable);
        return all;
    }

    @Override
    public QueryResults<ApRecordGainEntity> getPage(String userName, String recordProjectName, String status,
                                                    String recordUser, String recordTimeStart, String recordTimeEnd, String recordType, String recordProjectAddress, String reportStatus, Pageable pageable) {
        QApRecordGainEntity q = QApRecordGainEntity.apRecordGainEntity;
        com.querydsl.core.types.Predicate predicate = q.isNotNull().or(q.isNull());


        // 多条件查询：项目名称、状态、备案人员、备案申请开始时间、备案申请结束时间,备案类型等
        //备案类型区分：区域地震安全性评估成果/地震小区划工作成果
        if (!StringUtils.isEmpty(recordProjectAddress) && recordProjectAddress.contains("建设单位")) {
            String unitCode = constrService.findUnitCode(userName);
            predicate = ExpressionUtils.and(predicate, q.recordUnitCode.eq(unitCode));
        }
        if (!StringUtils.isEmpty(recordProjectAddress) && recordProjectAddress.contains("安评单位")) {
            predicate = ExpressionUtils.and(predicate, q.recordUser.eq(userName));
        }
        if (!StringUtils.isEmpty(recordProjectAddress) && recordProjectAddress.contains("中国")) {
            predicate = ExpressionUtils.and(predicate, q.reportStatus.eq(Constant.REPORT_STATUS_YES));
        }
        if (!StringUtils.isEmpty(recordProjectAddress) && !recordProjectAddress.contains("中国")
                && !recordProjectAddress.contains("安评单位") && !recordProjectAddress.contains("建设单位")) {
            predicate = ExpressionUtils.and(predicate, q.recordProjectAddress.like("%" + recordProjectAddress + "%"));
            predicate = ExpressionUtils.and(predicate, q.status.ne(Constant.CHECK_STATUS0));
        }
        predicate = (StringUtils.isEmpty(reportStatus)) ? predicate : ExpressionUtils.and(predicate, q.reportStatus.eq(reportStatus));
        predicate = ExpressionUtils.and(predicate, q.recordType.eq(recordType));
        predicate = (StringUtils.isEmpty(recordProjectName)) ? predicate : ExpressionUtils.and(predicate, q.recordProjectName.like("%" + recordProjectName + "%"));
        predicate = (StringUtils.isEmpty(status)) ? predicate : ExpressionUtils.and(predicate, q.status.like("%" + status + "%"));
        predicate = (StringUtils.isEmpty(recordUser)) ? predicate : ExpressionUtils.and(predicate, q.recordUser.like("%" + recordUser + "%"));
        if ((StringUtils.isEmpty(recordTimeStart)) && (!StringUtils.isEmpty(recordTimeEnd))) {
            Date endDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(recordTimeEnd + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, q.recordTime.loe(endDate));
        }
        if ((!StringUtils.isEmpty(recordTimeStart)) && (StringUtils.isEmpty(recordTimeEnd))) {
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(recordTimeStart+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, q.recordTime.goe(startDate));
        }
        if ((!StringUtils.isEmpty(recordTimeStart)) && (!StringUtils.isEmpty(recordTimeEnd))) {
            Date startDate = null;
            Date endDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(recordTimeStart+" "+"00:00:00.000");
                endDate = sf.parse(recordTimeEnd+" "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, q.recordTime.between(startDate, endDate));
        }
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE));

        return jpaQueryFactory
                .selectFrom(q)
                .where(predicate)
                .orderBy(
                        // 根据创建日期，降序排序
                        q.createTime.desc()
                )
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();
    }

    @Override
    @Transactional
    public void save(ApRecordGainEntity apRecordGainEntity) {
        // 状态初始化
        apRecordGainEntity.setDelFlag(Constant.NO_DELETE);
        //已提交待审核
        apRecordGainEntity.setStatus(Constant.CHECK_STATUS1);
        //未上报
        apRecordGainEntity.setReportStatus(Constant.REPORT_STATUS_NO);
        //未公告
        apRecordGainEntity.setRecordPublicStauts(Constant.PUBLICNO);
        apRecordGainEntity.setCreateTime(new Date());
        communityMapper.save(apRecordGainEntity);
        //调取待办接口
        ApTodoEntity apTodoEntity = new ApTodoEntity();
        apTodoEntity.setStatus(Constant.STATUSDB);
        apTodoEntity.setCreateTime(new Date());
        apTodoEntity.setDelFlag(Constant.NO_DELETE);
        apTodoEntity.setLinkId(apRecordGainEntity.getRecordId());
        apTodoEntity.setLocation(apRecordGainEntity.getRecordProjectAddress());
        // 0.区域地震安全性评估成果
        if (apRecordGainEntity.getRecordType().equals(Constant.REGINAL_EARTHQU)) {
            apTodoEntity.setTitle(apRecordGainEntity.getRecordProjectName() + "区域地震安全性评估成果审批");
            //去区域地震安全性评估成果审批页
            apTodoEntity.setUrl("../todolist/areadz.html");
        }
        // 1.地震小区划工作成果
        if (apRecordGainEntity.getRecordType().equals(Constant.EARTHQU_SUBDIVI)) {
            apTodoEntity.setTitle(apRecordGainEntity.getRecordProjectName() + "地震小区划工作成果审批");
            //去地震小区划工作成果审批页
            apTodoEntity.setUrl("../todolist/commun.html");
        }
        apTodoEntity.setCreatePerson(ServiceUtil.getLoginName(request));

        //审批的业务
        apTodoEntity.setTypeFlag(Constant.TYPRFLAGSS);
        apTodoEntity.setStation("项目审核员");
        apTodoService.saveDB(apTodoEntity);
    }

    @Override
    @Transactional
    public void zcsave(ApRecordGainEntity apRecordGainEntity) {
        // 状态初始化
        apRecordGainEntity.setDelFlag(Constant.NO_DELETE);
        //未提交
        apRecordGainEntity.setStatus(Constant.CHECK_STATUS0);
        //未上报
        apRecordGainEntity.setReportStatus(Constant.REPORT_STATUS_NO);
        //未公告
        apRecordGainEntity.setRecordPublicStauts(Constant.PUBLICNO);
        apRecordGainEntity.setCreateTime(new Date());
        communityMapper.save(apRecordGainEntity);

       /* //查询待办里有没有此业务暂存
        ApTodoEntity apTodoEntity = apTodoService.findByIdandType(apRecordGainEntity.getRecordId(), Constant.TYPEFLAGZC);
        if (apTodoEntity == null) {
            //调取待办接口
            apTodoEntity = new ApTodoEntity();
            apTodoEntity.setStatus(Constant.STATUSDB);
            apTodoEntity.setCreateTime(new Date());
            apTodoEntity.setDelFlag(Constant.NO_DELETE);
            apTodoEntity.setLinkId(apRecordGainEntity.getRecordId());
            apTodoEntity.setLocation(apRecordGainEntity.getRecordProjectAddress());
            // 0.区域地震安全性评估成果
            if(apRecordGainEntity.equals(Constant.REGINAL_EARTHQU)){
                apTodoEntity.setTitle(apRecordGainEntity.getRecordProjectName()+"区域地震安全性评估成果审批");
                //去区域地震安全性评估成果修改页
                apTodoEntity.setUrl("/regionrecord/update");
            }
            // 1.地震小区划工作成果
            if(apRecordGainEntity.equals(Constant.EARTHQU_SUBDIVI)){
                apTodoEntity.setTitle(apRecordGainEntity.getRecordProjectName()+"地震小区划工作成果审批");
                //去地震小区划工作成果修改页
                apTodoEntity.setUrl("/recordgain/update");
            }
            //暂存的业务
            apTodoEntity.setTypeFlag(Constant.TYPEFLAGZC);
            apTodoEntity.setCreatePerson("111");
            apTodoService.saveDB(apTodoEntity);
        }*/
    }

    @Override
    public ApRecordGainEntity queryApRecordGainById(String id) {
        ApRecordGainEntity apRecordGainEntity = communityMapper.findById(id).get();
        return apRecordGainEntity;
    }

    @Override
    public void update(ApRecordGainEntity apRecordGainEntity) {

    }

    @Override
    public void check(ApRecordGainEntity apRecordGainEntity) {
        //更新安评备案审批内容
        update(apRecordGainEntity);
        //查询待办里有没有此业务审批
        ApTodoEntity apTodoEntity = apTodoService.findByIdandType(apRecordGainEntity.getRecordId(), Constant.TYPRFLAGSS);
        if (apTodoEntity != null) {
            apTodoEntity.setStatus(Constant.STATUSYB);
            apTodoService.update(apTodoEntity);
        }
    }


    @Override
    public List<ApRecordGainEntity> getApRecordGainListByRecordLevel(String location, String recordType, String recordLevel) {
        QApRecordGainEntity qApRecordGainEntity = QApRecordGainEntity.apRecordGainEntity;
        List<ApRecordGainEntity> list = new ArrayList<ApRecordGainEntity>();
        if (!StringUtils.isEmpty(location) && location.contains(Constant.LOCATIONZG)) {
            list = jpaQueryFactory.selectFrom(qApRecordGainEntity).where(qApRecordGainEntity.recordLevel.eq(recordLevel),
                    qApRecordGainEntity.delFlag.eq(Constant.NO_DELETE), qApRecordGainEntity.status.eq(Constant.CHECK_STATUS3), qApRecordGainEntity.recordType.eq(recordType)).fetch();
        }
        if (!StringUtils.isEmpty(location) && !location.contains(Constant.LOCATIONZG)) {
            list = jpaQueryFactory.selectFrom(qApRecordGainEntity).where(qApRecordGainEntity.recordLevel.eq(recordLevel),
                    qApRecordGainEntity.delFlag.eq(Constant.NO_DELETE), qApRecordGainEntity.status.eq(Constant.CHECK_STATUS3), qApRecordGainEntity.recordProjectAddress.like("%" + location + "%"), qApRecordGainEntity.recordType.eq(recordType)).fetch();
        }
        return list;
    }

    @Override
    public void submit(ApRecordGainEntity apRecordGainEntity) {
        //更新安评备案
        update(apRecordGainEntity);
      /*  // 查询待办里有没有此业务暂存
        ApTodoEntity apTodoEntity=apTodoService.findByIdandType(apRecordGainEntity.getRecordId(),Constant.TYPEFLAGZC);
        if(apTodoEntity!=null){
            apTodoEntity.setStatus(Constant.STATUSYB);
            apTodoService.update(apTodoEntity);
        }*/
        //调取待办接口
        ApTodoEntity apTodoEntity = new ApTodoEntity();
        apTodoEntity.setStatus(Constant.STATUSDB);
        apTodoEntity.setCreateTime(new Date());
        apTodoEntity.setDelFlag(Constant.NO_DELETE);
        apTodoEntity.setLinkId(apRecordGainEntity.getRecordId());
        apTodoEntity.setLocation(apRecordGainEntity.getRecordProjectAddress());
        // 0.区域地震安全性评估成果
        if (apRecordGainEntity.getRecordType().equals(Constant.REGINAL_EARTHQU)) {
            apTodoEntity.setTitle(apRecordGainEntity.getRecordProjectName() + "区域地震安全性评估成果审批");
            //去区域地震安全性评估成果审批页
            apTodoEntity.setUrl("../todolist/areadz.html");
        }
        // 1.地震小区划工作成果
        if (apRecordGainEntity.getRecordType().equals(Constant.EARTHQU_SUBDIVI)) {
            apTodoEntity.setTitle(apRecordGainEntity.getRecordProjectName() + "地震小区划工作成果审批");
            //去地震小区划工作成果审批页
            apTodoEntity.setUrl("../todolist/commun.html");
        }

        apTodoEntity.setCreatePerson(ServiceUtil.getLoginName(request));
        //审批的业务
        apTodoEntity.setTypeFlag(Constant.TYPRFLAGSS);
        apTodoEntity.setStation("项目审核员");
        apTodoService.saveDB(apTodoEntity);
    }
    @Override
    public void cancel(ApRecordGainEntity apRecordGainEntity) {
        //更新安评备案审批内容
        update(apRecordGainEntity);
        //查询待办里有没有此业务审批
        ApTodoEntity apTodoEntity = apTodoService.findByIdandType(apRecordGainEntity.getRecordId(), Constant.TYPRFLAGSS);
        if (apTodoEntity != null) {
            apTodoMapper.delete(apTodoEntity);
        }
    }
    @Override
    @Transactional
    public void addHandle(ApPublicEntity pub, String RecordType) {
        pub.setCreateUser(ServiceUtil.getLoginName(request));
        pub.setOrganName(ServiceUtil.getOrgName(request));
        pub.setRevokeg(Constant.REVOKE_NO);
        pub.setDelFlag(Constant.NO_DELETE);
        pub.setCreateTime(new Date());
        pub.setInputenTime(new Date());
        //0.区域地震安全性评估成果
        if (RecordType.equals(Constant.REGINAL_EARTHQU)) {
            pub.setPublicUrl("/dzjap/recordgain/getRecordgain");
        }
        //1.地震小区划工作成果
        if (RecordType.equals(Constant.EARTHQU_SUBDIVI)) {
            pub.setPublicUrl("/dzjap/regionrecord/getRegionRecord");
        }
        //公开公告状态为：6
        pub.setFictionType("6");
        try {
            publicDao.save(pub);

            //调取待办接口
            ApTodoEntity apTodoEntity = new ApTodoEntity();
            apTodoEntity.setStatus(Constant.STATUSDB);
            apTodoEntity.setCreateTime(new Date());
            apTodoEntity.setDelFlag(Constant.NO_DELETE);
            apTodoEntity.setTitle(pub.getTitle() + "公开公告审批");
            apTodoEntity.setLinkId(pub.getPublicId());
            //审批员才能看到相应的审批
            apTodoEntity.setStation("地震部门审定人员");
            //去审批页
            //0.区域地震安全性评估成果
            if(RecordType.equals(Constant.REGINAL_EARTHQU)){
                apTodoEntity.setUrl("../todolist/publick.html");
            }
            //1.地震小区划工作成果
            if(RecordType.equals(Constant.EARTHQU_SUBDIVI)){
                apTodoEntity.setUrl("../todolist/publick.html");
            }
            apTodoEntity.setLocation(pub.getOrganName());
            apTodoEntity.setCreatePerson(ServiceUtil.getLoginName(request));
            //审批的业务
            apTodoEntity.setTypeFlag(Constant.TYPRFLAGSS);
            apTodoService.saveDB(apTodoEntity);
            //修改小区划和区域地震拟制公告状态为已拟制
            ApRecordGainEntity apRecordGainEntity = queryApRecordGainById(pub.getRelationId());
            apRecordGainEntity.setRecordPublicStauts(Constant.PUBLICYES);
            update(apRecordGainEntity);
        } catch (Exception e) {

        }
    }

    @Override
    public ApRecordGainEntity queryByProName(String proName) {
        if (!StringUtils.isEmpty(proName)) {
            QApRecordGainEntity q = QApRecordGainEntity.apRecordGainEntity;
            return jpaQueryFactory.selectFrom(q).where(q.recordProjectName.eq(proName), q.delFlag.eq(Constant.NO_DELETE)).fetchOne();
        }
        return null;
    }
    @Override
    public List queryAllRecordGain(){
        QApRecordGainEntity q = QApRecordGainEntity.apRecordGainEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE)) ;
        List<ApRecordGainEntity> list = jpaQueryFactory.selectFrom(q)
                .where(predicate)
                .orderBy(q.createTime.desc())
                .fetch();
        return list;
    }
}
